package com.youhome.service.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youhome.common.exception.CustomException;
import com.youhome.common.response.ResultCode;
import com.youhome.service.mapper.BTemplateHtmlSelectedMapper;
import com.youhome.service.model.*;
import com.youhome.service.service.BCompanyService;
import com.youhome.service.service.BTemplateHtmlModuleValueService;
import com.youhome.service.service.BTemplateHtmlSelectedService;
import com.youhome.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by chen365 on 2018/1/8.
 */
@Service
public class BTemplateHtmlSelectedServiceImpl implements BTemplateHtmlSelectedService {
    @Autowired
    private BCompanyService bCompanyService;
    @Autowired
    private BTemplateHtmlModuleValueService bTemplateHtmlModuleValueService;
    @Autowired
    private BTemplateHtmlSelectedMapper bTemplateHtmlSelectedMapper;

    @Override
    public int insertSelective(BTemplateHtmlSelected record) {
        return bTemplateHtmlSelectedMapper.insertSelective(record);
    }

    @Override
    public BTemplateHtmlSelected selectByPrimaryKey(Long id) {
        return bTemplateHtmlSelectedMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateStatus(BTemplateHtmlSelected record) {
        return bTemplateHtmlSelectedMapper.updateByPrimaryKeySelective(record);
    }


    @Override
    @Transactional
    public int save(BTemplateHtmlSelected entity) {
        System.err.println("BTemplateHtmlSelected:" + entity.toString());
        if (entity.getId() == null) {
            //保存模版数据
            entity.setStatus(1); //草稿
            entity.setIssue(false); //未发布
            entity.setEnabled(true); //可用
            entity.setCtime(new Date());
            bTemplateHtmlSelectedMapper.insertSelective(entity);
            Long select_id = entity.getId();

            //保存模块数据
            List<BTemplateHtmlModuleValue> modules = entity.getModules();
            for (BTemplateHtmlModuleValue module : modules) {
                module.setSelectId(select_id);
                bTemplateHtmlModuleValueService.insertSelective(module);
            }

            //下面的方法我故意让其出现空指针异常，会事物回滚
            //String string  = null;
            //if(string.equals("")) {
            //  int i = 0;
            //}
        } else {
            //修改
            entity.setUtime(new Date());
            bTemplateHtmlSelectedMapper.updateByPrimaryKeySelective(entity);
            Long select_id = entity.getId();
            //保存模块数据
            List<BTemplateHtmlModuleValue> modules = entity.getModules();

            bTemplateHtmlModuleValueService.deleteBySelectId(select_id); //删除原有模块数据

            for (BTemplateHtmlModuleValue module : modules) {

//                if (module.getId() != null) {
//                    //原有模块
//                    bTemplateHtmlModuleValueService.updateByPrimaryKeySelective(module);
//                } else {
//                    //新增模块
//                    module.setSelectId(select_id);
//                    bTemplateHtmlModuleValueService.insertSelective(module);
//                }

                module.setSelectId(select_id);
                bTemplateHtmlModuleValueService.insertSelective(module); //新增模块数据
            }
        }
        return 1;
    }

    @Override
    public void publishUnPublish(Principal principal, Long id) throws CustomException {
        if (StringUtils.isEmpty(id)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }
        Long userId = principal.getUser().getUserId();
        BCompany bCompany = bCompanyService.selectByUserId(userId);
        if (bCompany == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        Long companyId = bCompany.getCompanyId();

        BTemplateHtmlSelected bTemplateHtmlSelected = bTemplateHtmlSelectedMapper.selectByPrimaryKey(id);

        //是否已经通过审核
        if (bTemplateHtmlSelected.getStatus() != 4) {
            throw new CustomException(ResultCode.UNAPPROVED);
        }
        //只能提交是自己的数据
        if (bTemplateHtmlSelected.getCompanyId() != bCompany.getCompanyId()) {
            throw new CustomException(ResultCode.DO_NOT_HAVE_PERMISSION);
        }
        //是否已经发布
        if (!bTemplateHtmlSelected.getIssue()) {
            //判断是否有已经发布的,如果有,则关闭
            if (bTemplateHtmlSelectedMapper.selectIssueCountByCompanyId(companyId) > 0) {
                //取消已经发布的
                bTemplateHtmlSelectedMapper.updateCancelIssueByCompanyId(companyId);
            }
        }
        if (bTemplateHtmlSelectedMapper.updateIssueByPrimaryKey(id) <= 0) {
            throw new CustomException(ResultCode.NO_DATA);
        }
    }

    @Override
    public void submitAudit(Principal principal, Long id) throws CustomException {
        if (StringUtils.isEmpty(id)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }

        Long userId = principal.getUser().getUserId();

        BCompany bCompany = bCompanyService.selectByUserId(userId);
        if (bCompany == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }

        BTemplateHtmlSelected record = new BTemplateHtmlSelected();

        record.setId(id);
        record.setStatus(2);

        BTemplateHtmlSelected bTemplateHtmlSelected = bTemplateHtmlSelectedMapper.selectByPrimaryKey(id);
        //只有为草稿的才能提交审核
        if (bTemplateHtmlSelected.getStatus() != 1) {
            throw new CustomException(ResultCode.DO_NOT_HAVE_PERMISSION);
        }
        //只能提交是自己的数据
        if (bTemplateHtmlSelected.getCompanyId() != bCompany.getCompanyId()) {
            throw new CustomException(ResultCode.DO_NOT_HAVE_PERMISSION);
        }

        if (bTemplateHtmlSelectedMapper.updateByPrimaryKeySelective(record) <= 0) {
            throw new CustomException(ResultCode.FAIL);
        }

    }

    @Override
    public BTemplateHtmlSelected previewSecondaryHomePage(Principal principal, Long id) throws CustomException {
        if (StringUtils.isEmpty(id)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }

        Long userId = principal.getUser().getUserId();
        BCompany bCompany = bCompanyService.selectByUserId(userId);
        if (bCompany == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        BTemplateHtmlSelected bTemplateHtmlSelected = bTemplateHtmlSelectedMapper.selectByPrimaryKey(id);
        //只能操作自己的数据
        if (bTemplateHtmlSelected.getCompanyId() != bCompany.getCompanyId()) {
            throw new CustomException(ResultCode.DO_NOT_HAVE_PERMISSION);
        }
        return bTemplateHtmlSelected;
    }

    @Override
    public PageInfo<BTemplateHtmlSelected> selectByBean(Principal principal, Integer status, Integer pageNumber, Integer pageSize) throws CustomException {

        Long userId = principal.getUser().getUserId();
        BCompany bCompany = bCompanyService.selectByUserId(userId);
        if (bCompany == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        BTemplateHtmlSelected record = new BTemplateHtmlSelected();

        record.setCompanyId(bCompany.getCompanyId());
        if (!StringUtils.isEmpty(status)) {
            record.setStatus(status);
        }
        if (pageNumber == null || pageNumber < 1) {
            pageNumber = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNumber, pageSize);
        List<BTemplateHtmlSelected> list = bTemplateHtmlSelectedMapper.selectByBean(record);
        return new PageInfo<>(list);
    }

    @Override
    public BTemplateHtmlSelected selectIssueByUUID(String uuid) throws CustomException {
        if (StringUtils.isEmpty(uuid)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }
        BCompany bCompany = bCompanyService.selectByUUID(uuid);
        if (bCompany == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        Long companyId = bCompany.getCompanyId();
        BTemplateHtmlSelected bTemplateHtmlSelected = bTemplateHtmlSelectedMapper.selectIssueByCompanyId(companyId);
        return bTemplateHtmlSelected;
    }

    @Transactional
    @Override
    public void save(Principal principal,String data) throws CustomException {
        if (!StringUtils.isEmpty(data)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }

        BTemplateHtmlSelected entity = JsonUtils.json2Bean(data, BTemplateHtmlSelected.class);

        if (StringUtils.isEmpty(entity.getTempId())) {
            throw new CustomException(ResultCode.NOT_TEMPLATE);
        }

        if (entity.getModules().size() <= 0 || entity.getModules() == null) {
            throw new CustomException(ResultCode.NOT_TEMPLATE_MODULE_DATA);
        }


        Long userId = principal.getUser().getUserId();
        BCompany bCompany = bCompanyService.selectByUserId(userId);
        if (bCompany == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        Long companyId = bCompany.getCompanyId();

        entity.setCompanyId(companyId);


        System.err.println("BTemplateHtmlSelected:" + entity.toString());
        if (entity.getId() == null) {
            //保存模版数据
            entity.setStatus(1); //草稿
            entity.setIssue(false); //未发布
            entity.setEnabled(true); //可用
            entity.setCtime(new Date());
            bTemplateHtmlSelectedMapper.insertSelective(entity);
            Long select_id = entity.getId();

            //保存模块数据
            List<BTemplateHtmlModuleValue> modules = entity.getModules();
            for (BTemplateHtmlModuleValue module : modules) {
                module.setSelectId(select_id);
                bTemplateHtmlModuleValueService.insertSelective(module);
            }

            //下面的方法我故意让其出现空指针异常，会事物回滚
            //String string  = null;
            //if(string.equals("")) {
            //  int i = 0;
            //}
        } else {
            //修改
            entity.setUtime(new Date());
            bTemplateHtmlSelectedMapper.updateByPrimaryKeySelective(entity);
            Long select_id = entity.getId();
            //保存模块数据
            List<BTemplateHtmlModuleValue> modules = entity.getModules();

            bTemplateHtmlModuleValueService.deleteBySelectId(select_id); //删除原有模块数据

            for (BTemplateHtmlModuleValue module : modules) {

//                if (module.getId() != null) {
//                    //原有模块
//                    bTemplateHtmlModuleValueService.updateByPrimaryKeySelective(module);
//                } else {
//                    //新增模块
//                    module.setSelectId(select_id);
//                    bTemplateHtmlModuleValueService.insertSelective(module);
//                }

                module.setSelectId(select_id);
                bTemplateHtmlModuleValueService.insertSelective(module); //新增模块数据
            }
        }

    }


}
